<template>
    <!--重新规划-->
    <div class="mainDiv">
        <h3 style="color: #000;text-align: center;padding: 5px 0;">选择部门</h3>
        <el-tree :data="data" :props="defaultProps" node-key="id" :default-expanded-keys="expandedKeys" show-checkbox check-strictly @check="checkNode" ref="tree" style="height: 100%;overflow: auto;">
        </el-tree>
        <div style="padding: 10px;background-color: #e4e3e3;text-align: center">
            <el-button type="success" size="mini" @click="submit">选择</el-button>
        </div>
    </div>
</template>
<script>
import C from '@/common/common.js'

export default {
  name: 'selectDepartment',
  data () {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      expandedKeys: []
    }
  },
  methods: {
    // 获取机构下所有分店和部门列表
    async getDepartmentList () {
      let list = await C.ajax('/organization/user/getDepartmentList')
      // 整合树状图
      if (list.length) {
        list = this.makeTree(list)
      }
      this.data = list
      console.log(list)
    },
    // 制作树状图
    makeTree (list) {
      let idList = list.map(row => row.id)
      let newList = list.filter(row => idList.indexOf(row.pid) < 0)
      this.expandedKeys = newList.map(row => row.id)
      console.log(this.expandedKeys)
      this.creatTree(newList, list)
      return newList
    },
    creatTree (newList, list) {
      newList.forEach(row => {
        for (let i = 0; i < list.length; i++) {
          if (list[i].pid == row.id) {
            row.children = row.children || []
            row.children.push(list[i])
          }
        }
        if (row.children && row.children.length) {
          this.creatTree(row.children, list)
        }
      })
    },
    checkNode (a, b) {
      this.$refs.tree.setCheckedKeys([a.id])
    },
    submit () {
      C.closeBrowserWindow(this.$refs.tree.getCheckedNodes()[0])
    }
  },
  mounted: function () {
    this.getDepartmentList()
  }
}
</script>
<style>

</style>